const express = require("express");
const app = express();
const mysql = require("mysql");
var connection = mysql.createConnection({
  host: "192.168.11.131",
  user: "root",
  password: "patpat",
  database: "patpat",
});

connection.connect(function (err) {
  if (err) {
    console.error("链接失败: " + err.stack);
    return;
  }
  startServer();
  console.log("链接成功 connection id : " + connection.threadId);
});

// connection.end();
const startServer = () => {
  app.listen(8080, (err) => {
    console.log(err);
    if (err) {
      connection.end(); // 关闭数据库
      console.log("服务启动失败");
    } else {
      console.log("服务启动成功");
    }
  });
};

// 查询数据库验证码
app.get("/code", async (req, res) => {
  const data = await getCode();
  res.status = 200;
  res.send(data);
});
const getCode = async () => {
  return new Promise((resole, reject) => {
    connection.query(
      "select * from oms_phone_verify order by created_at desc limit 10;",
      function (error, results, fields) {
        if (error) throw error;
        resole(results[0]);
        console.log("查询结果：", results[0].code, fields[0]);
      }
    );
  });
};
